import { defineStore } from 'pinia';
import { setToken, removeToken } from '@/utils/token';
import {loginApi, logoutApi} from '@/api/auth';

interface UserState {
    username: string;
    token: string | null;
    isLogin: boolean;
}

export const useUserStore = defineStore('user', {
    state: (): UserState => ({
        username: '',
        token: null,
        isLogin: false
    }),
    actions: {
        // 登录动作
        async login(username: string, password: string) {
            const response = await loginApi(username, password);
            console.log(response);
            if (response.code === 0 ) {
                this.token = response.data;
                this.username = username;
                this.isLogin = true;
                setToken(response.data); // 存储Token到localStorage
                return true;
            }
            return false;
        },
        // 注销动作
        async logout() {
            try {
                // 调用后端登出接口（即使失败也继续清除本地状态）
                await logoutApi();
            } catch (error) {
                console.error('登出接口调用失败:', error);
            } finally {
                // 清除本地状态和Token
                this.username = '';
                this.token = null;
                this.isLogin = false;
                removeToken();
            }
        }
    }
});
